import os
from struct import pack
import ResolveWar3
import re
import configparser

def i2id(number):
    s2id_list = [str(i) for i in range(0,10)] + [chr(i) for i in range(65,91)]
    list = []
    list.append(number)
    _str = ""

    while True:
        if list[len(list) - 1] <= 35:
            break 

        for i in range(len(list)):
            if list[i] > 35:
                list.append(list[i] // 36)
                list[i] = list[i] % 36

        
    for i in range(len(list)):
        _str = s2id_list[list[i]] + _str
    return _str

def ReturnMainPath(func):
    def wrapper(*args):
        result = func(*args)
        os.chdir(os.path.abspath(os.path.dirname(os.getcwd())))
        return result
    return wrapper

# 获取主目录下所有文件
@ReturnMainPath
def get_model_path():
    r_list = []
    os.chdir('resource')

    for root, dirs, files in os.walk("."):
        for file in files:
            if '.mdx' in file.lower() or '.mdl' in file.lower():
                r_list.append((root + '\\' + file)[2:].replace("\\",r"\\"))

    return r_list

# 判断当前工作目录是否在lni格式的魔兽内
def is_lni():
    if not os.path.exists(LniMapPath+'\\resource') :
        os.mkdir(LniMapPath + '\\resource',777)
    r_list = ['resource','map','table']
    files = os.listdir()
    for file in r_list:
        if file not in files :
            return False
    return True

def can_w2l():
    return os.path.exists(w2lPath)

# 生成unit.ini
@ReturnMainPath
def CreateUnitini(modle_list):
    r_str = ""
    os.chdir('table')
    len_model_list = len(modle_list)
    for i in range(len_model_list):
        r_str = r_str +"[h" + i2id(i).rjust(3,"0") + "]\n"
        r_str += '_parent = "hpea"\n-- 名字\n'
        r_str += 'Name = "模型单位"\n-- 模型文件\n'
        r_str += 'file = "' + modle_list[i] + '"\n\n' 

    with open("unit.ini","w+",encoding = "utf-8") as fi:
        fi.write(r_str)

    return len_model_list

map_width = 480*64
map_height = 480*64
@ReturnMainPath
def CreateDoodadini(modle_list):
    global map_width
    global map_height
    r_str = ""
    os.chdir('table')
    # load lni
    with open('w3i.ini','r',encoding = "utf-8") as fe:
        data = fe.read()
    pattern = re.compile('地图.度.+')
    xy = pattern.findall(data)
    map_width = int(re.search('[0-9]+',xy[0]).group())*64
    map_height = int(re.search('[0-9]+',xy[1]).group())*64
    # Create ini
    len_model_list = len(modle_list)
    for i in range(len_model_list):
        r_str = r_str +"[D" + i2id(i).rjust(3,"0") + "]\n"
        r_str += '_parent = "IOic"\n-- 名字\n'
        r_str += 'Name = "模型单位"\n-- 模型文件\n'
        r_str += 'file = "' + modle_list[i] + '"\n'
        r_str += '-- 固定角度\nfixedRot = -1.0000\n'
        r_str += '-- 最大比例\nmaxScale = 10.0000\n'
        r_str += '-- 最小比例\nminScale = 0.01\n'
        r_str += '-- 模型文件 - 样式总数\nnumVar = 1\n'

    with open("doodad.ini","w+",encoding = "utf-8") as fi:
        fi.write(r_str)

    return len_model_list


# 生成War3MapUnits.doo
@ReturnMainPath
def CreateWar3MapUnits_doo(units):
    def CreateUnit():
        unit_number = 0
        def CreateUnit0(id,x,y):
            nonlocal unit_number
            is_sloc = id == "sloc"
            obj = pack("4s",id.encode("utf-8"))
            obj += pack("i",0)
            obj += pack("3f",x,y,0.0)
            obj += pack("f",4.7123894691467285)
            obj += pack("3f",1.0,1.0,1.0)
            obj += pack("b",2)
            obj += pack("i",0)
            obj += pack("2b",0,0)
            if is_sloc :
                obj += pack("2i",0,0)
            else:
                obj += pack("2i",-1,-1)
            obj += pack("i",-1)
            obj += pack("i",0)
            if is_sloc :
                obj += pack("ifi",0,0.0,0) #gold
            else:
                obj += pack("ifi",12500,-1.0,1) #gold
            obj += pack("9i",0,0,0,0,0,0,1,-1,-1)
            obj += pack("i",unit_number)
            unit_number += 1
            return obj
        return CreateUnit0
    # 设置工作目录
    os.chdir('map')
    # 声明
    obj = pack("4s","W3do".encode("utf-8"))
    obj += pack("2i",8,11)
    obj += pack("i",units + 1)
    # 地图尺寸 / 2
    size_max = 224*64
    # 单位间隔(默认700)(建筑或环境模型最好1000-1500)
    size = 1500
    # 模型坐标
    origin = (size_max *2 - int(size_max*2//size) * size) / 2
    if origin <= size / 2:
        origin = size / 2
    modelUnitX = -size_max + origin
    modelUnitY = -size_max + origin

    CU = CreateUnit()
    obj += CU("sloc",0,0.0)
    for i in range(units):
        modelUnitX += size
        if modelUnitX >= size_max:
            modelUnitX = -size_max + origin
            modelUnitX += size
            modelUnitY += size
        
        obj += CU("h" + i2id(i).rjust(3,"0"),modelUnitX,modelUnitY)
    
    with open("war3mapUnits.doo","wb") as fi:
        fi.write(obj)

@ReturnMainPath
def CreateWar3MapDoodads_doo(doodads):
    # 设置工作目录
    os.chdir('map')
    # 地图尺寸 / 2
    size_max = map_width
    # 单位间隔(默认700)(建筑或环境模型最好1000-1500)
    size = 1500
    # 模型坐标
    origin = (size_max *2 - int(size_max*2//size) * size) / 2
    if origin <= size / 2:
        origin = size / 2
    modelDoodadX = -size_max + origin
    modelDoodadY = -size_max + origin

    doodadList = []
    for i in range(doodads):
        modelDoodadX += size
        if modelDoodadX >= size_max:
            modelDoodadX = -size_max + origin
            modelDoodadX += size
            modelDoodadY += size

            if modelDoodadY >= map_height:
                print(('单位 %d Y轴越界') % ('D' + i2id(i).rjust(3,"0")))

        doodad = {
            'ID' : 'D' + i2id(i).rjust(3,"0"),
            '位置 X' : modelDoodadX,
            '位置 Y' : modelDoodadY,
            '缩放 X' : 3.0,
            '缩放 Y' : 3.0,
            '缩放 Z' : 3.0,
            '生命' : -1,
        }
        doodadList.append(doodad)
        Bytes = ResolveWar3.packDoodad_doo(doodadList)
        with open("war3map.doo","wb") as fi:
            fi.write(Bytes)

#settings
cf = configparser.ConfigParser()
cf.read('config.ini',encoding="utf-8-sig")

w2lPath = cf.get('path','w2lPath')
#lni地图路径
LniMapPath = cf.get('path','LniMapPath')
#输出
MapExportPath = cf.get('path','MapExportPath')

def main(Mapname):
    if not can_w2l():
        print("没有w2l")
        os.system('pause')
        return
    os.chdir(LniMapPath)
    if not is_lni() :
        print("不是lni地图或错误的位置")
        os.system('pause')
        return
    # print("本程序用于制作模型地图使用\n请把模型文件放入到'packfile\\resource'文件夹中\n360会报毒\n\tby欲死")
    CreateWar3MapDoodads_doo(CreateDoodadini(get_model_path()))
    # CreateWar3MapUnits_doo(CreateUnitini(get_model_path()))
    print("完成")
    args1 = LniMapPath
    args2 = MapExportPath + "\\" + Mapname
    os.system(w2lPath + " obj " + args1 + " " + args2)
    # os.system(w2lPath + " lni " + args1)

if __name__ == '__main__':
    main('ModelMap.w3x')